﻿using UnityEngine;
using System.Collections;
using System;

public class WebCameraScript : MonoBehaviour
{
    private WebCamTexture webCameraTexture;


}


public class WebCamManager
{
    private WebCamTexture webCameraTexture;

    private static WebCamManager _instance;

    public static WebCamManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new WebCamManager();
            }
            return _instance;
        }
    }

    private WebCamManager()
    {

    }

    public IEnumerator OpenCamera(Action<WebCamTexture> onFinish, bool isBack = true)
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        { 
            for (int cameraIndex = 0; cameraIndex < WebCamTexture.devices.Length; cameraIndex++)
            {
                var device = WebCamTexture.devices[cameraIndex];
                if (device.isFrontFacing != isBack)
                {
                    var deviceName = device.name;
                    if (webCameraTexture)
                    {
                        webCameraTexture.Stop(); 
                    }
                    // Screen.width > Screen.height ? new WebCamTexture(deviceName, Screen.height, Screen.width ) : 
                    webCameraTexture = new WebCamTexture(deviceName){requestedWidth = Screen.height,requestedHeight = Screen.width};
                }
            }
            if (webCameraTexture)
            {
                webCameraTexture.Play();
                onFinish(webCameraTexture);
            }
            else
            {
                Debug.LogError("No what you need camera found");
            }
        }
    }

    public void Play()
    {
        if (webCameraTexture)
        {
            webCameraTexture.Play();
        }
    }

    public void Pause()
    {
        if (webCameraTexture)
        {
            webCameraTexture.Pause();
        }
    }

    public void Stop()
    {
        if (webCameraTexture)
        {
            webCameraTexture.Stop();
        }
    }


    #region Property

    public WebCamTexture Texture
    {
        get { return webCameraTexture; }
    }

    public bool IsPlaying
    {
        get { return webCameraTexture.isPlaying; }
    }




    #endregion

}
